import { Injectable, UnauthorizedException } from '@nestjs/common';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import { SignInDto } from './dto/sign-in.dto';
import { UserService } from '../user/user.service';
import { UserRolesPermsVo } from '../user/vo/user-roles-perms.vo';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
  ) {}

  /**
   * 登录
   * @param signInDto
   */
  async signIn(signInDto: SignInDto): Promise<any> {
    const user = await this.userService.getOneByUsername(signInDto.username);
    if (!user) {
      throw new Error('用户不存在');
    }
    if (user.status === 0) {
      throw new Error('用户被禁用,请联系管理员');
    }
    if (!(await bcrypt.compare(signInDto.password, user.password))) {
      throw new UnauthorizedException('密码错误');
    }
    // 获取用户的roles和用户的roles对应的perms
    // payload需要为存对象
    const payload = { ...(await this.userService.findRolesAndPerms(user.id)) };
    return {
      accessToken: await this.jwtService.signAsync(payload),
    };
  }

  /**
   *  获取登陆后req中的user
   * @param req
   * @private
   */
  getReqUser(req: Request) {
    const user = req['user'];
    if (user) {
      return user as UserRolesPermsVo;
    }
    throw new Error('req中的user不存在');
  }
}
